import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';

const excel = {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8',
  extension: 'csv',
  fileAccept: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};


// 默认配置项
let CONFIG: XLSX.Sheet2JSONOpts = {
  defval: '', // 空值默认为 ''
  raw: false, // 是否格式化
  blankrows: false  // 忽略空行
};

/** 定义抽象类 */
export abstract class ExcelModel {
  abstract export(json: any[], fileName: string): void;
  abstract read(file: Blob): Promise<any>;
}






/**
 * 处理上传下载excel文件
 */

@Injectable({
  providedIn: 'root'
})
export class ExcelService extends ExcelModel {

  constructor() {
    super();
  }

  /** 导出excel文件 */
  export(json: any[], fileName: string): void {
    debugger
    const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, fileName);
    const fullName = `${fileName}_export_${new Date().getTime()}.${excel.extension}`;
    XLSX.writeFile(workbook, fullName);
  }


  /**
   * @description: 读取excel文件
   * @param file blob类型
   * @param config 设置读取excel文件的格式，XLSX.Sheet2JSONOpts 类型
   */
  read(file: Blob | File, config?: XLSX.Sheet2JSONOpts): Promise<any> {
    if (config) {
      CONFIG = Object.assign(CONFIG, config); // 自定义配置项
    }
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    // const JSON_OBJ = {};
    return new Promise((resolve) => {
      reader.onload = () => {
        const data = reader.result;
        const workbook = XLSX.read(data, { type: 'binary' });
        // 这里只读取一个 sheet
        workbook.SheetNames.forEach((sheetName) => {
          const XL_ROW_OBJECT = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], CONFIG);
          resolve(XL_ROW_OBJECT); // 只会执行一次 即传第一个sheet
        });
      };
    });
  }
}
